import L from 'leaflet'
import 'static/js/L.Control.MousePosition.js'
// 小地图
import 'static/js/Control.MiniMap.js'
// 比例尺
import 'static/js/leaflet.nauticscale.min.js'
// 全屏控制
import 'static/js/Control.FullScreen.js'
// 打印地图
import 'static/js/leaflet.browser.print.js'
import 'static/js/leaflet.browser.print.utils.js'
import 'static/js/leaflet.browser.print.sizes.js'

// 地图平移
import 'static/js/L.Control.Pan.js'
// 地图缩放级别
import 'static/js/L.Control.Zoominfo.js'
// 量尺
import 'static/js/leaflet-ruler.js'
// 面积测量
import 'static/js/leaflet-measure.js'

// 船高亮
import 'static/js/leaflet.marker.highlight.js'

import 'static/js/leaflet.polylineDecorator.js'

// 绘制所需要的文件
import 'static/js/draw-lib/Leaflet.draw.js'
import 'static/js/draw-lib/Toolbar.js'
import 'static/js/draw-lib/Tooltip.js'

import 'static/js/draw-lib/ext/TouchEvents.js'
import 'static/js/draw-lib/ext/GeometryUtil.js'
import 'static/js/draw-lib/ext/LatLngUtil.js'
import 'static/js/draw-lib/ext/LineUtil.Intersect.js'
import 'static/js/draw-lib/ext/Polyline.Intersect.js'
import 'static/js/draw-lib/ext/Polygon.Intersect.js'

import 'static/js/draw-lib/draw/DrawToolbar.js'
import 'static/js/draw-lib/draw/handler/Draw.Feature.js'
import 'static/js/draw-lib/draw/handler/Draw.SimpleShape.js'
import 'static/js/draw-lib/draw/handler/Draw.Circle.js'
import 'static/js/draw-lib/draw/handler/Draw.Marker.js'
import 'static/js/draw-lib/draw/handler/Draw.Polyline.js'
import 'static/js/draw-lib/draw/handler/Draw.Polygon.js'
import 'static/js/draw-lib/draw/handler/Draw.Rectangle.js'

import 'static/js/draw-lib/edit/EditToolbar.js'
import 'static/js/draw-lib/edit/handler/EditToolbar.Edit.js'
import 'static/js/draw-lib/edit/handler/EditToolbar.Delete.js'
import 'static/js/draw-lib/edit/handler/Edit.Poly.js'
import 'static/js/draw-lib/edit/handler/Edit.SimpleShape.js'
import 'static/js/draw-lib/edit/handler/Edit.Circle.js'
import 'static/js/draw-lib/edit/handler/Edit.Marker.js'
import 'static/js/draw-lib/edit/handler/Edit.Rectangle.js'

import 'static/js/draw-lib/Control.Draw.js'

// 绘制控件
import 'static/js/leaflet-control-draw.js'

// 业务图层控件
import 'static/js/leaflet-control-buslayer.js'

// 清除控件
import 'static/js/leaflet-control-clear.js'

// 轨迹
import mapTrickUtil from 'static/js/MapTrickUtil.js'

import '@static/js/leaflet-iconcontrol.js'

// 海图3中模式切换
import 'static/js/leaflet.groupedlayercontrol.js'
import 'static/js/basemaps.js'
import drag from '@/utils/drag'

import * as mabardCoordService from '@/services/MabardCoordService'
import * as keyAreaService from '@/services/KeyAreaService'
import * as shipService from '@/services/ShipService'

import drawShip from './DrawShip'

var parentobj
var mapobj
var mapClickShipSpeed // 点击地图上船舶符号时带的onve的航速

export function createMap (homeObj) {
  parentobj = this
  // 全屏控制
  this.map = new L.Map('mapshipmap', {
    fullscreenControl: true,
    fullscreenControlOptions: {
      position: 'topright'
    },
    zoominfoControl: true,
    zoomControl: false,
    attributionControl: true,
    layers: [MapData.Basemaps.all]
  })

  drawShip.init(this.map)
  drawShip.on('shipOnClick', shipOnClick)
  mapobj = this.map
  initMap()

  this.map.on('moveend', (e) => {
    // this.prevTime = 0
    // this.prevDraw = 0
    mapZoomEndMoveEnd()
  })
  this.map.on('zoomend', (e) => {
    // this.prevTime = 0
    // this.prevDraw = 0
    mapZoomEndMoveEnd()
  })
  this.map.on('onMapClearClick', (e) => {
    clearMapObject(e)
  })
  // if (this.mapindex == 0) {
  //   this.time(this.map)
  // }
  drawMarineDepartmentRange() // 显示海事处范围，就是那些红线和绿圆圈
  showOrganiza() // 显示海事机构，例如 长岛海事处

  drag(this.$refs.ship_detail_title, this.$refs.ship_detail)

  // mapDrawUtil.setDrawMap(mapobj);
  // initDrawFun();
}

export function locateShip(mmsi, showInfoPage) {
  drawShip.locateShip(mmsi, showInfoPage)
}

// 初始化地图
function initMap () {
  parentobj.osm = new L.TileLayer(parentobj.$config.OSM_URL, parentobj.$config.OSM_OPTION)
  mapobj.addLayer(parentobj.osm)

  // 船位瓦片
  parentobj.shipTile = new L.TileLayer(parentobj.$config.SHIP_URL, parentobj.$config.SHIP_OPTION)
  mapobj.addLayer(parentobj.shipTile)

  mapobj.setView(new L.LatLng(37.8, 120.7), 8)

  // 小地图
  var miniTile = new L.TileLayer(parentobj.$config.OSM_URL, parentobj.$config.MINI_OPTION)
  var miniMap = new L.Control.MiniMap(miniTile, {
    toggleDisplay: true,
    minimized: true
  }).addTo(mapobj)

  // 鼠标经纬度
  L.control.mousePosition().addTo(mapobj)

  // 比例尺
  mapobj.addControl(new L.Control.ScaleNautic({
    metric: true,
    imperial: false,
    nautic: true
  }))

  // 打印地图
  L.control.browserPrint({
    // position: 'bottomright',
    position: 'topright',
    printModes: ['Portrait', 'Landscape'],
    closePopupsOnPrint: false,
    printModesNames: {
      Portrait: '纵向',
      Landscape: '横向'
    }
  }).addTo(mapobj)
}

function shipOnClick (ship) {
  parentobj.shipdetail = true
  shipService.getDetial(ship.terminalCode, this.shipName).then(ret => {
    parentobj.retinfo = convertDetial(ret)

    if (parentobj.retinfo.ship) {
      parentobj.boatinfo = parentobj.retinfo.ship
    } else {
      parentobj.shipEnName = ship.shipName
    }
    if (parentobj.retinfo.ais) {
      if (parentobj.retinfo.ais.trueheading === -1) {
        parentobj.retinfo.ais.trueheading = parentobj.retinfo.ais.course
      }
      parentobj.boatAis = parentobj.retinfo.ais
      if (parentobj.retinfo.ais.utc) {
        parentobj.boatinfo.operatetime = new Date(parentobj.retinfo.ais.utc * 1000).pattern('yyyy-MM-dd hh:mm:ss')
      }
    }
  })
}

// 清除地图上相关对象
function clearMapObject (e) {
  mapTrickUtil.clearTrick(mapobj)
}

// 烟台海事局各海事处海域管辖范围，
function drawMarineDepartmentRange () {
  parentobj.$config.getManagementArea().forEach(area => {
    if (area.pos) {
      let label = L.divIcon({className: 'area_label', html: `<div>${area.name}</div>`})
      L.marker(area.pos, {icon: label}).addTo(mapobj)
    }
    if (area.points) {
      L.polyline(area.points, {color: 'red', weight: 1}).addTo(mapobj)
      for (var i = 0; i < area.points.length; i++) {
        L.circleMarker(area.points[i], {
          radius: 4,
          fillColor: 'LightGreen',
          color: 'Green',
          weight: 1,
          opacity: 1,
          fillOpacity: 1
        }).addTo(mapobj)

        L.circleMarker(area.points[i], {
          radius: 0,
          color: 'Green',
          weight: 1,
          opacity: 1,
          fillOpacity: 1
        }).addTo(mapobj)
      }
    }
  })
}

// 获取海事处
function getOrganiza () {
  return mabardCoordService.getAll()
}

// 海图上显示各个海事处标签，蓝色海事处名称标签
function showOrganiza () {
  getOrganiza().then((mabs) => {
    for (let i = 0; i < mabs.length; i++) {
      let markeroption = {}
      markeroption.className = ''
      let mab = mabs[i]
      if (mab.organiza.orgCode === '160000') {
        markeroption.html = '<div class="my-label">' + mab.organiza.name + '</div>'
        let myIcon = L.divIcon(markeroption)
        let markertemp = L.marker([37.7, 121.4], {icon: myIcon})
        parentobj.tooltip.push(markertemp)
        markertemp.addTo(mapobj)
      } else {
        markeroption.html = '<div class="my-label">' + mab.organiza.name + '</div>'
        let myIcon = L.divIcon(markeroption)
        let markertemp = L.marker([mab.latitude, mab.longitude], {icon: myIcon})
        parentobj.tooltip.push(markertemp)
        markertemp.addTo(mapobj)
      }
    }
  })
}

// 关注区域添加
function keyAreaClick (e) {
  parentobj.$prompt('请输入重点区域名称', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^[\s\S]*.*[^\s][\s\S]*$/,
    inputErrorMessage: '重点区域名不能为空'
  }).then(async ({
                   value
                 }) => {
    let name = value
    let lon = e.latlng.lng
    let lat = e.latlng.lat
    let usierid = parentobj.$profile.id

    let retobj = await keyAreaService.createKeyArea(name, lon, lat, usierid)
    if (retobj != null && retobj != 'null') {
      parentobj.tianjia = false
      document.getElementById('mapshipmap').style.cursor = '-webkit-grab'
      document.getElementById('mapshipmap').style.cursor = '-moz-grab'
      parentobj.gengxin++
      parentobj.$alert('添加成功！')
    } else {
      parentobj.$alert('添加失败！')
    }
  }).catch(() => {
    parentobj.gengxin++
    parentobj.tianjia = false
    document.getElementById('mapshipmap').style.cursor = '-webkit-grab'
    document.getElementById('mapshipmap').style.cursor = '-moz-grab'
    parentobj.$message('您已取消此次添加')
  })
}

// 查询船舶详情后对象的转换
function convertDetial (retinfod) {
  if (retinfod) {
    let retinfod1 = {}
    let ship = {}
    ship.id = retinfod.id
    ship.shipNameCn = retinfod.cnName
    ship.shipNameEn = retinfod.enName
    ship.mmsi = retinfod.mmsi
    ship.shipClass = retinfod.shipClass
    ship.shipTypeNameCn = retinfod.typeNameCn
    ship.shipImo = retinfod.imo
    ship.shipCallsign = retinfod.callsign
    ship.shipRouteCode = retinfod.routeCode
    ship.sailingareaName = retinfod.sailingAreaName
    ship.shipGrosston = retinfod.grossTonnage
    ship.shipNetton = retinfod.netTonnage
    ship.shipLength = retinfod.shipLength
    ship.shipBreadth = retinfod.shipWidth
    ship.shipDepth = retinfod.shipDepth
    ship.shipPassengerNum = retinfod.passengerCount
    ship.shpParkingNum = retinfod.parkingCount
    ship.shipWindLevel = retinfod.windLevel
    ship.rescueEquipmentNum = retinfod.rescueEqMax
    ship.minSafeManningNum = retinfod.safeManningMin
    ship.regportName = retinfod.regPortName
    ship.shipOwner = retinfod.owner
    ship.shipOperator = retinfod.operator
    ship.shipEnginePower = retinfod.enginePower
    ship.shipEngineNum = retinfod.engineCount
    ship.engineTypeNameCn = retinfod.engineTypeNameCn
    ship.shipNo = retinfod.shipNo
    ship.shipRegNo = retinfod.regNo
    ship.shipId = retinfod.shipCode

    retinfod1.ship = ship
    retinfod1.ais = retinfod.ais || {}
    // retinfod1.ais.speed = mapClickShipSpeed
    return retinfod1
  } else {
    let retinfod1 = {}
    retinfod1.ship = null
    // retinfod1.ais = null;
    retinfod1.ais = {}
    // retinfod1.ais.speed = mapClickShipSpeed
    return retinfod1
  }
}

/* 轨迹线有关 */
export function showTrack (parent) {
  mapTrickUtil.setShowGpsLabel(true)
  mapTrickUtil.showTrackInfo(mapobj, parentobj.tracklist)
}

function mapZoomEndMoveEnd () {
  mapTrickUtil.mapZoomEndMoveEndForTrick(mapobj)
}
export function clearShipTrick (parent) {
  mapTrickUtil.clearTrick(mapobj)
}
// export function showGpsLabel(parent){
//   mapTrickUtil.setShowGpsLabel(true);
//   mapTrickUtil.convertGpsTimeLabelAndShow(mapobj);
// }
// export function hideGpsLabel(parent){
//   mapTrickUtil.setShowGpsLabel(false);
//   mapTrickUtil.clearGpsLabelMapObj(mapobj);
// }

function formatStr (numberRound, roundDigit) { // 四舍五入，保留位数为roundDigit
  if (numberRound.indexOf('.') >= 0) {
    var alllen = numberRound.length
    var lencz = alllen - numberRound.indexOf('.')
    var xswall = lencz - 1
    if (xswall <= roundDigit) {
      return numberRound
    } else {
      var indexend = numberRound.indexOf('.') + roundDigit + 1
      return numberRound.substr(0, indexend)
    }
  } else {
    return numberRound
  }
}
